package com.leetcode.partition12;

import java.io.*;
import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2022/1/31 18:02
 */
public class LC1168水资源分配优化 {

    private static final int N = 10010, M = 2 * N;
    private static int[][] edges = new int[M][3];

    private static int n = 0, idx = 0;
    private static int[] parent = new int[N];

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[] wells = new int[n];
        int[][] pipes = new int[m][3];
        ss = reader.readLine().split(" ");
        for (int i = 0; i < n; i++) wells[i] = Integer.parseInt(ss[i]);
        for (int i = 0; i < m; i++) {
            ss = reader.readLine().split(" ");
            int a = Integer.parseInt(ss[0]), b = Integer.parseInt(ss[1]), c = Integer.parseInt(ss[2]);
            pipes[i] = new int[]{a, b, c};
        }
        writer.write(minCostToSupplyWater(n, wells, pipes) + "\n");
        writer.flush();
    }

    public static int minCostToSupplyWater(int n, int[] wells, int[][] pipes) {
        //wells转化为一个超级源点0到各个节点需要的边权
        for (int i = 0; i < n; i++) edges[idx++] = new int[]{0, i + 1, wells[i]};
        for (int i = 0; i < pipes.length; i++) edges[idx++] = pipes[i];
        for (int i = 0; i < N; i++) parent[i] = i;
        int ans = 0;
        Arrays.sort(edges, 0, idx, (o1, o2) -> Integer.compare(o1[2], o2[2]));
        for (int i = 0; i < idx; i++) {
            int a = edges[i][0], b = edges[i][1], c = edges[i][2];
            int x = find(a), y = find(b);
            if (x != y) {
                parent[x] = y;
                ans += c;
            }
        }
        return ans;
    }

    private static int find(int x) {
        if (x == parent[x]) return x;
        return parent[x] = find(parent[x]);
    }
}
